// 压力性损伤相关收集表
import { Button, Modal, DatePicker, Form, Row, Radio, Col, Cascader, Input, Select, InputNumber, message } from 'antd'
import { FormInstance } from 'antd/es/form/Form'
import React, { useState, useEffect, useMemo } from 'react'
import { useRecoilValue } from 'recoil'
import moment from 'moment'
import { cloneDeep } from 'lodash'
import BaseTitle from '../BaseTitle'
import styles from './index.module.less'
import { dictValues } from '@/store/dicts'
import { userInfo } from '@/store/userInfo'
import { isNullData } from '@/utils'
import request from '@/utils/request'
import InputItem from './component/InputItem'

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    lg: { span: 7 },
    md: { span: 24 },
  },
  wrapperCol: {
    xs: { span: 24 },
    lg: { span: 14 },
    md: { span: 24 },
  },
}

const pressure = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
}

interface IProps {
  formObj: FormInstance // form实例
  handleOk: (value: boolean) => void // 确认回调, 需要判断是直接关闭还是继续添加不关闭
  handleCancel: () => void // 取消或者关闭回调
  visible: boolean // 控制弹窗的展示和因此
  onlyLook?: boolean // 为true只读, 不可编辑
  isEdit?: boolean // 是否为编辑状态
  wardList?: any // 有级联信息传进来就用, 没有就自己获取
  hospitalId?: string
}

interface IBottom {
  label: string
  name: string
  form: FormInstance
  help?: string
  pass?: boolean
}

const App: React.FC<IProps> = (props: IProps) => {
  const { formObj, handleOk, handleCancel, visible, onlyLook = false, isEdit = false, wardList, hospitalId } = props

  // 底部损伤部位数数据结构
  const bottomCount = [
    {
      label: '2期',
      name: 'two',
      form: formObj,
      pass: true,
    },
    {
      label: '3期',
      name: 'three',
      form: formObj,
      pass: true,
    },
    {
      label: '4期',
      name: 'four',
      form: formObj,
      pass: true,
    },
    {
      label: '深部组织损伤',
      name: 'deep',
      form: formObj,
      pass: true,
    },
    {
      label: '不可分期',
      name: 'noStage',
      form: formObj,
      pass: true,
    },
    {
      label: '黏膜压力性损伤',
      name: 'sticky',
      form: formObj,
      pass: true,
    },
  ]
  // 用户信息
  const userMsg = useRecoilValue(userInfo)
  const [curWardList, setCurWardList] = useState<any>([])
  const [bottomArr, setBottomArr] = useState<IBottom[]>(bottomCount)

  // 递归函数，将原始数据转换为 Cascader 数据结构
  const transformDataCatalogue = (items: any) =>
    items.map((item: any) => {
      const dis = item.type === '20' && item.endemicAreaVos.length === 0
      const cascaderItem: any = {
        label: item.unit,
        value: item.id.toString(),
        disabled: dis,
      }
      if (item.endemicAreaVos.length > 0) {
        cascaderItem.children = transformDataCatalogue(item.endemicAreaVos)
      }
      return cascaderItem
    })

  // 获取病区级联
  const getWardHandle = async () => {
    const params = {
      hospitalId,
    }
    const res = await request.post('/wardManage/getOrganization', params)
    if (isNullData(res) && res.data) {
      setCurWardList(transformDataCatalogue(res.data.endemicAreaVos))
    }
  }

  // 确认回调
  const confirmHandle = (type: boolean) => {
    const allPass = bottomArr.every((item) => item.pass)
    const sum = formObj.getFieldValue('twoAboveTotalNumber')
    const twoAbovePhaseNumber = formObj.getFieldValue('twoAbovePhaseNumber')
    if (sum !== twoAbovePhaseNumber) {
      message.error({ content: '入本病区24小时后新发2期及以上院内压力性损伤部位数与总数不一致', duration: 4 })
      return
    }
    if (!allPass) {
      message.error('有器械相关数量大于对应的部位总数')
      return
    }
    handleOk(type)
  }

  // 枚举内容
  const enumDict = useRecoilValue(dictValues)
  const today = moment().endOf('day')
  // 自定义禁用规则
  const disabledDate = (current) => current && current > today
  const footer = onlyLook ? null : (
    <div className={styles.footerWrapper}>
      {!onlyLook && (
        <>
          {!isEdit && <Button onClick={() => confirmHandle(false)}>确定并继续填写</Button>}

          <Button
            type='primary'
            onClick={() => {
              confirmHandle(true)
            }}
          >
            确定
          </Button>
        </>
      )}
    </div>
  )
  const washOption = (options: { label: string; value: string }[]) =>
    options.map((item) => ({
      ...item,
      value: Number(item.value),
    }))

  // 根据输入的内容判断大小给出提示
  const checkSize = (type: string, first?: number, second?: number) => {
    const curIndex = bottomArr.findIndex((item) => item.name === type)
    if (curIndex > -1) {
      const copyArr = [...bottomArr]
      if ((first || 0) < (second || 0)) {
        copyArr.splice(curIndex, 1, { ...copyArr[curIndex], pass: false })
      } else {
        copyArr.splice(curIndex, 1, { ...copyArr[curIndex], pass: true })
      }
      setBottomArr(copyArr)
    }
  }

  // 合计
  const getAll = (changeValue: any, changeAllValue: any) => {
    const sumLeft =
      (changeAllValue.twoPhaseNumber || 0) +
      (changeAllValue.threePhaseNumber || 0) +
      (changeAllValue.fourPhaseNumber || 0) +
      (changeAllValue.deepPhaseNumber || 0) +
      (changeAllValue.noStagePhaseNumber || 0) +
      (changeAllValue.stickyPhaseNumber || 0)
    const sumRight =
      (changeAllValue.twoInstrumentNumber || 0) +
      (changeAllValue.threeInstrumentNumber || 0) +
      (changeAllValue.fourInstrumentNumber || 0) +
      (changeAllValue.deepInstrumentNumber || 0) +
      (changeAllValue.noStageInstrumentNumber || 0) +
      (changeAllValue.stickyInstrumentNumber || 0)
    formObj.setFieldsValue({ twoAboveTotalNumber: sumLeft, instrumentTotalNumber: sumRight })
    if (changeValue.twoPhaseNumber || changeValue.twoInstrumentNumber) {
      checkSize('two', changeAllValue.twoPhaseNumber, changeAllValue.twoInstrumentNumber)
    }
    if (changeValue.threePhaseNumber || changeValue.threeInstrumentNumber) {
      checkSize('three', changeAllValue.threePhaseNumber, changeAllValue.threeInstrumentNumber)
    }
    if (changeValue.fourPhaseNumber || changeValue.fourInstrumentNumber) {
      checkSize('four', changeAllValue.fourPhaseNumber, changeAllValue.fourInstrumentNumber)
    }
    if (changeValue.deepPhaseNumber || changeValue.deepInstrumentNumber) {
      checkSize('deep', changeAllValue.deepPhaseNumber, changeAllValue.deepInstrumentNumber)
    }
    if (changeValue.noStagePhaseNumber || changeValue.noStageInstrumentNumber) {
      checkSize('noStage', changeAllValue.noStagePhaseNumber, changeAllValue.noStageInstrumentNumber)
    }
    if (changeValue.stickyPhaseNumber || changeValue.stickyInstrumentNumber) {
      checkSize('sticky', changeAllValue.stickyPhaseNumber, changeAllValue.stickyInstrumentNumber)
    }
  }

  // 关闭
  const cancelHandle = () => {
    const resetArr = bottomArr.map((item) => ({
      ...item,
      help: '',
    }))
    setBottomArr(resetArr)
    handleCancel()
  }

  const init = async () => {
    await getWardHandle()
  }
  useEffect(() => {
    if (visible && (!wardList || !wardList.length)) {
      init()
    }
  }, [wardList, visible])

  return (
    <>
      <Modal
        className={styles.pressure}
        title='压力性损伤相关收集表'
        width={930}
        open={visible}
        onCancel={cancelHandle}
        footer={footer}
        centered
      >
        <div className={styles.pressureWrapper} id='pressureInjury'>
          <Form
            onValuesChange={getAll}
            disabled={onlyLook}
            name='time_related_controls'
            {...formItemLayout}
            form={formObj}
          >
            <BaseTitle text='患者基本信息' style={{ marginBottom: '24px' }} />
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  rules={[{ required: true, message: '请选择发生病区名称' }]}
                  name='happenArea'
                  label='发生病区名称'
                >
                  <Cascader
                    options={wardList && wardList.length ? wardList : curWardList}
                    placeholder='请输入发生病区名称'
                    getPopupContainer={(): any => document.getElementById('pressureInjury')}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  rules={[{ required: true, message: '请输入住院患者病案号' }]}
                  className={styles.right}
                  name='patientNumber'
                  label='住院患者病案号'
                >
                  <Input placeholder='请输入住院患者病案号' />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  rules={[{ required: true, message: '请选择入院时间' }]}
                  name='admissionTime'
                  label='入院时间'
                >
                  <DatePicker
                    getPopupContainer={(): any => document.getElementById('pressureInjury')}
                    disabledDate={disabledDate}
                    placeholder='请选择入院时间'
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  rules={[{ required: true, message: '请选择性别' }]}
                  className={styles.right}
                  name='sex'
                  label='性别'
                >
                  <Radio.Group>
                    <Radio value={0}>男</Radio>
                    <Radio value={1}>女</Radio>
                  </Radio.Group>
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item name='age' label='年龄' rules={[{ required: true, message: '请选择年龄' }]}>
                  <Select
                    getPopupContainer={(): any => document.getElementById('pressureInjury')}
                    placeholder='请输入年龄'
                    options={washOption(enumDict.age)}
                    // listHeight={200}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item
                  rules={[{ required: true, message: '请选择发生日期' }]}
                  className={styles.right}
                  name='happenDate'
                  label='发生日期'
                >
                  <DatePicker
                    getPopupContainer={(): any => document.getElementById('pressureInjury')}
                    disabledDate={disabledDate}
                    placeholder='请选择发生日期'
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
            </Row>
            <BaseTitle text='压力性损伤信息' style={{ marginBottom: '24px' }} />

            <div className={styles['pressure-form']}>
              <Form.Item
                rules={[{ required: true, message: '请选择' }]}
                name='assessmentTool'
                {...pressure}
                label='压力性损伤风险评估工具：'
              >
                <Select
                  getPopupContainer={(): any => document.getElementById('pressureInjury')}
                  placeholder='请选择压力性损伤风险评估工具'
                  options={washOption(enumDict.assessment_tool)}
                />
              </Form.Item>
              <Form.Item
                rules={[{ required: true, message: '请选择' }]}
                name='isEvaluate'
                label='入病区时是否进行压力性损伤风险评估'
                {...pressure}
              >
                <Radio.Group>
                  <Radio value={0}>是</Radio>
                  <Radio value={1}>否</Radio>
                </Radio.Group>
              </Form.Item>
              <Form.Item
                rules={[{ required: true, message: '请选择' }]}
                {...pressure}
                name='evaluateType'
                label='入病区时压力性损伤风险评估级别'
              >
                <Select
                  placeholder='请选择入病区时压力性损伤风险评估级别'
                  options={washOption(enumDict.assessment_level)}
                  getPopupContainer={(): any => document.getElementById('pressureInjury')}
                />
              </Form.Item>
              <Form.Item
                rules={[{ required: true, message: '请选择' }]}
                {...pressure}
                name='evaluateHappenTime'
                label='最近1次压力性损伤风险评估距离发现时间：'
              >
                <Select
                  getPopupContainer={(): any => document.getElementById('pressureInjury')}
                  placeholder='请选择最近1次压力性损伤风险评估距离发现时间：'
                  options={washOption(enumDict.distance_time)}
                />
              </Form.Item>
              <Form.Item
                rules={[{ required: true, message: '请选择' }]}
                {...pressure}
                name='latelyEvaluateType'
                label='最近1次压力性损伤风险评估级别：'
              >
                <Select
                  placeholder='请选择最近1次压力性损伤风险评估级别：'
                  options={washOption(enumDict.assessment_level)}
                  getPopupContainer={(): any => document.getElementById('pressureInjury')}
                />
              </Form.Item>
              <Form.Item
                {...pressure}
                name='twoAbovePhaseNumber'
                label='入本病区24小时后新发2期及以上院内压力性损伤部位数'
                rules={[{ required: true, message: '请输入' }]}
              >
                <InputNumber
                  controls={false}
                  placeholder='入本病区24小时后新发2期及以上院内压力性损伤部位数'
                  style={{ width: '100%' }}
                  precision={0}
                  min={1}
                />
              </Form.Item>
            </div>

            <div className={styles.table}>
              <div className={styles['table-info']}>
                <div className={styles.left}>分期、类型</div>
                <div className={styles.firstContent}>入本病区24小时后新发2期及以上院内压力性损伤部位数</div>
                <div className={styles.content}>其中，医疗器械相关压力性损伤部位数</div>
              </div>
              {bottomCount.map((item) => (
                <InputItem key={item.name} label={item.label} name={item.name} wrapperForm={item.form} />
              ))}
              <div className={styles['table-info']}>
                <div className={styles.left}>合计</div>
                <div className={styles.firstContent}>
                  <Form.Item wrapperCol={{ span: 24 }} name='twoAboveTotalNumber'>
                    <InputNumber disabled controls={false} placeholder='请输入' />
                  </Form.Item>
                </div>
                <div className={styles.content}>
                  <Form.Item wrapperCol={{ span: 24 }} name='instrumentTotalNumber'>
                    <InputNumber disabled controls={false} placeholder='请输入' />
                  </Form.Item>
                </div>
              </div>
            </div>
          </Form>
        </div>
      </Modal>
    </>
  )
}

export default App
